/*
 * =============================================================================
 * "THE BEER-WARE LICENSE" (Revision 42):
 * <eirikb@google.com> wrote this file. As long as you retain this notice you
 * can do whatever you want with this stuff. If we meet some day, and you think
 * this stuff is worth it, you can buy me a beer in return Eirik Brandtzæg
 * =============================================================================
 */
package no.eirikb.robotec.server;

import java.io.IOException;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * A Blocking server
 * @author eirikb
 * @author <a href="mailto:eirikb@google.com">eirikb@google.com</a>
 */
public class Server extends Thread {

    private Socket socket;
    private ServerAction action;
    private boolean run;
    private final int LAG_SLEEP = 10;

    public Server(Socket socket, ServerAction action) {
        this.socket = socket;
        this.action = action;
        run = true;
    }

    public Socket getSocket() {
        return socket;
    }

    public String getIP() {
        return socket.getInetAddress().getHostAddress();
    }

    public void setRun(boolean run) {
        this.run = run;
    }

    public void close() {
        run = false;
        try {
            socket.close();
        } catch (IOException ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void sendText(String line) {
        try {
            socket.getOutputStream().write((line + '\n').getBytes());
        } catch (IOException ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public void sendLagText(String line) {
        for (char c : line.toCharArray()) {
            try {
                socket.getOutputStream().write(("" + c).getBytes());
                Thread.sleep(LAG_SLEEP);
            } catch (InterruptedException ex) {
                Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    @Override
    public void run() {
        try {
            while (run) {
                action.onServerRead(this, socket.getInputStream().read());
            }
        } catch (IOException ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                socket.close();
                action.onServerDisconnect(this);
            } catch (IOException ex) {
                Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}
